import {
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Injectable
} from '@nestjs/common'
import { map, Observable } from 'rxjs'
import { Logger } from '../utils/log4js'
import { Log } from 'src/modules/log/entities/log.entity' // 导入 Log 实体
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { DateUtil } from 'src/utils'
import { Staff } from 'src/modules/staff/entities/staff.entity'

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  constructor(
    @InjectRepository(Log) private readonly log: Repository<Log>,
    @InjectRepository(Staff) private readonly staff: Repository<Staff>
  ) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.getArgByIndex(1).req

    return next.handle().pipe(
      map(async data => {
        const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
          Request original url: ${req.originalUrl}
          Method: ${req.method}
          IP: ${req.ip}
          User: ${JSON.stringify(req.user)}
          Response data:${JSON.stringify(data)}
          <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<`

        Logger.info(logFormat)
        Logger.access(logFormat)

        // 保存日志信息到数据库
        const log = new Log()
        const id = req.user ? req.user.id : data ? data.id : null
        id && (log.staff = await this.staff.findOne({ where: { id } }))
        log.url = req.originalUrl
        log.method = req.method
        log.ip = req.ip
        log.code = 200
        log.date = new DateUtil(new Date(), 'yyyy-MM-dd hh:mm:ss').format()
        await this.log.save(log)
        return data
      })
    )
  }
}
